import React, { Component } from 'react'
import {
  Card,
  Breadcrumb,
  Form,
  Radio,
  Button,
  DatePicker,
  Table,
  Image,
  Tag,
  Space,
  Modal,
  message,
} from 'antd'
import { ArticleListState } from 'api/constant.js'
import { Link } from 'react-router-dom'
import { getArticles, removeArticles } from 'api/articles'
import defaultImage from 'assets/error.png'
import MyChannel from 'components/MyChannel'

import {
  EditOutlined,
  DeleteOutlined,
  ExclamationCircleOutlined,
} from '@ant-design/icons'

const { RangePicker } = DatePicker
const { confirm } = Modal

export default class ArticleList extends Component {
  state = {
    articles: [],
    currentPage: 1,
    pageSize: 10,
    total: 0,
    isLoading: false,
  }
  params = {} // 用于存储发送请求的数据
  columns = [
    {
      title: '封面',
      dataIndex: 'cover',
      render(value, rowItem, index) {
        const { type, images } = value
        if (type === 0) {
          return (
            <Image
              width={200}
              height={150}
              src={defaultImage}
              preview={false}
            ></Image>
          )
        } else {
          return (
            <Image
              width={200}
              height={150}
              src={images[0]}
              fallback={defaultImage}
            ></Image>
          )
        }
      },
    },
    {
      title: '标题',
      dataIndex: 'title',
      width: '240',
    },
    {
      title: '状态',
      dataIndex: 'status',
      render(value) {
        const itemObj = ArticleListState.find((item) => item.id === value)
        return <Tag color={itemObj.color}>{itemObj.name}</Tag>
      },
    },
    {
      title: '发布时间',
      dataIndex: 'pubdate',
    },
    {
      title: '阅读数量',
      dataIndex: 'read_count',
    },
    {
      title: '评论条数',
      dataIndex: 'comment_count',
    },
    {
      title: '点赞',
      dataIndex: 'like_count',
    },
    {
      title: '操作',
      render: (value, rowItem, index) => {
        return (
          <>
            <Space>
              <Button
                type="primary"
                shape="circle"
                icon={<EditOutlined />}
                onClick={() => this.handleEdit(rowItem.id)}
              ></Button>
              <Button
                type="primary"
                shape="circle"
                danger
                icon={<DeleteOutlined />}
                onClick={() => this.handleDel(rowItem.id)}
              ></Button>
            </Space>
          </>
        )
      },
    },
  ]
  componentDidMount() {
    this.getArticlesList()
  }

  async getArticlesList() {
    this.setState({ isLoading: true })
    const { currentPage, pageSize } = this.state
    const { data } = await getArticles({
      page: currentPage,
      per_page: pageSize,
      ...this.params,
    })
    this.setState({
      articles: data.results,
      currentPage: data.page,
      pageSize: data.per_page,
      total: data.total_count,
      isLoading: false,
    })
  }
  render() {
    const { articles, total, currentPage, pageSize, isLoading } = this.state
    return (
      <div className="articleList">
        {/* 表单数据 */}
        <Card
          title={
            <Breadcrumb>
              <Breadcrumb.Item>
                <Link to="/home">首页</Link>
              </Breadcrumb.Item>
              <Breadcrumb.Item>内容管理</Breadcrumb.Item>
            </Breadcrumb>
          }
        >
          <Form onFinish={this.onFinish} initialValues={{ status: undefined }}>
            <Form.Item label="状态" name="status">
              <Radio.Group>
                {ArticleListState.map((item, index) => (
                  <Radio key={index} value={item.id}>
                    {item.name}
                  </Radio>
                ))}
              </Radio.Group>
            </Form.Item>
            {/* 频道 */}
            <Form.Item label="频道" name="channel_id">
              <MyChannel></MyChannel>
            </Form.Item>
            <Form.Item label="日期" name="date">
              <RangePicker />
            </Form.Item>
            <Form.Item>
              <Button type="primary" htmlType="submit">
                筛选
              </Button>
            </Form.Item>
          </Form>
        </Card>
        {/* 表格数据 */}
        <Card title={`根据筛选条件功查询到 ${total} 条结果`}>
          <Table
            loading={isLoading}
            dataSource={articles}
            columns={this.columns}
            rowKey="id"
            pagination={{
              position: ['bottomCenter'],
              current: currentPage,
              pageSize: pageSize,
              total: total,
              onChange: this.onChange,
            }}
          />
          ;
        </Card>
      </div>
    )
  }
  // 点击-筛选-筛选数据
  onFinish = (values) => {
    // 利用axios原理 对 undefined null不处理
    // 处理状态数据
    // if (values.status !== -1) {
    //   this.params.status = values.status
    // } else {
    //   delete this.params.status
    // }
    this.params.status = values.status
    // 处理频道数据
    // if (values.channel_id !== undefined) {
    //   this.params.channel_id = values.channel_id
    // } else {
    //   delete this.params.channel_id
    // }
    this.params.channel_id = values.channel_id
    // 时间数据处理
    this.params.begin_pubdate =
      values.date && values.date[0].startOf('day').format('YYYY-MM-DD HH:mm:ss')
    this.params.end_pubdate =
      values.date && values.date[1].endOf('day').format('YYYY-MM-DD HH:mm:ss')
    this.getArticlesList()
  }
  onChange = (current, pageSize) => {
    this.setState(
      {
        currentPage: current,
        pageSize: pageSize,
        articles: [],
      },
      () => {
        this.getArticlesList()
      }
    )
  }
  // 删除-删除当前数据
  handleDel = (id) => {
    console.log(id)
    confirm({
      title: '温馨提示',
      icon: <ExclamationCircleOutlined />,
      content: '亲~ 您是否要确定删除这条数据？',
      onOk: async () => {
        await removeArticles(id)
        message.success('恭喜~,删除成功')
        this.getArticlesList()
      },
      onCancel() {
        console.log('Cancel')
      },
    })
  }
  handleEdit = (id) => {
    this.props.history.push(`/home/publish/${id}`)
  }
}
